package com.example.hosptial.repository;

import com.example.hosptial.model.enity.Patient;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.query.Procedure;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository
public interface PatientRepository extends JpaRepository<Patient, Integer> {

    // 根据医生ID获取患者列表
    @Query(value = "SELECT * FROM patient WHERE doctorId = :doctorId ORDER BY patientId", nativeQuery = true)
    List<Patient> findByDoctorDoctorId(@Param("doctorId") String doctorId);

    // 根据医生ID和患者姓名模糊查询
    @Query(value = "SELECT * FROM patient WHERE doctorId = :doctorId AND patientName LIKE CONCAT('%', :patientName, '%')", nativeQuery = true)
    List<Patient> findByDoctorDoctorIdAndPatientNameContaining(@Param("doctorId") String doctorId, @Param("patientName") String patientName);

    // 获取患者详细信息（使用存储过程）
    @Query(value = "CALL GetPatientDetails(:inputPatientId)", nativeQuery = true)
    Map<String, Object> getPatientDetails(@Param("inputPatientId") Integer inputPatientId);

    // 病人入院（使用存储过程）
    @Modifying
    @Query(value = "CALL admit_patient(:patientName, :patientGender, :patientAge, " +
           ":patientIdCard, :patientPhone, :conditionDesc, :doctorId, :bedId)", nativeQuery = true)
    void admitPatient(
        @Param("patientName") String patientName,
        @Param("patientGender") String patientGender,
        @Param("patientAge") Integer patientAge,
        @Param("patientIdCard") String patientIdCard,
        @Param("patientPhone") String patientPhone,
        @Param("conditionDesc") String conditionDesc,
        @Param("doctorId") String doctorId,
        @Param("bedId") Integer bedId
    );

    // 病人出院（使用存储过程）
    @Modifying
    @Query(value = "CALL delete_patient(:Id)", nativeQuery = true)
    void dischargePatient(@Param("Id") Integer patientId);

    // 病人转床（使用存储过程）
    @Modifying
    @Query(value = "CALL transfer_bed(:Id, :b)", nativeQuery = true)
    void transferBed(
        @Param("Id") Integer patientId,
        @Param("b") Integer newBedId
    );

    @Modifying
    @Query(value = "CALL admit_patient(?1, ?2)", nativeQuery = true)
    void updateBedStatus(Integer bedId, Integer patientId);
}